<?php

/**
 * <li>Title: user.php</li>
 * <li>Project: Niu</li>
 * <li>Package: /app/models/</li>
 * <li>Description: models of user's validation </li>
 * <li>Copyright: Copyright (c) 2008</li>
 * <li>Company: Infolex LLC </li>
 * <li>Created on 2009-5-20</li>
 *
 * @author lei_gao
 * @version 1.0
 */
class Product extends AppModel
{
	var $name='Product';

	function cloneProduct($pid) {
	    $sql = 'select * from g_products where g_id = '.intval($pid);
	    $data = $this->query($sql);
	    if (empty($data)) {
	        return ;
	    } ;
	    $p = $data['0']['g_products'];
	    
	    unset($p['g_id']);
	    $p['g_timestart'] = date('Y-m-d H:i:s');
	    $p['in_list'] = 0;
	    $this->save($p, false);
	   
	}
	function deletePhoto($pid, $picid) {
	    $pid = intval($pid);
	    if ($picid<=0) {
	        return ;
	    }
	    $name = SystemProperties::$img_names[$picid];
	    if (empty($name)) {
	        return ;
	    }
	    $sql = "update g_products set `{$name}`=NULL where g_id = {$pid}";
	    //echo $sql;
	    $this->query($sql);
	}
	function selectProductInfo($prenum,$sql){
		$number=SystemProperties::$product_pageNumber;
		return $this->query("select * from g_products  where $sql order by in_list desc,g_cat desc,g_hot desc,popularity  desc  limit $prenum,$number");
	}
	function selectProductInfoLast($prenum,$sql){
		$number=SystemProperties::$product_pageNumber;
		return $this->query("select * from g_products  where $sql order by g_id desc  limit $prenum,$number");
	}
	function deleteProduct($key){
		$this->query("delete from g_products where g_id in($key)");
	}
	function updateProductInList($pid,$in_list){
		$pid = intval($pid);
		$in_list = intval($in_list);
		$this->query("update g_products set in_list = '{$in_list}' where g_id = {$pid} ");
	}
	
	
	function selectProduct($id){
		return $this->query("select * from g_products  where g_id=$id");
	}
	function selectMoreProduct($ids){
		return $this->query("select * from g_products  where g_id in($ids)");
	}
	function updateProduct($id,$sql){
		$this->query("update g_products set $sql where g_id=$id");
	}
	function getMaxID(){
		$liberary_ary = $this->query('select last_insert_id() as liberary_id',false);
		return  $liberary_ary[0][0]['liberary_id']+1;
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $pid
	 * @param unknown_type $type //$type : 0 all   1 unuse  2 used
	 * @param unknown_type $order //id or time(领取时间)
	 * @param unknown_type $p
	 * @param unknown_type $n
	 */
	function getCouponList($pid, $type, $order, $p, $n, &$total) {
	    $pid = intval($pid);
	    if ($type == 2) {
	        $where = ' and uid>0 ';
	    } elseif ($type == 1) {
	        $where = ' and uid=0 ';
	    } else {
	        $where = '';
	    }
	    $order = ($order!='id')?'time':'id';
	    $p = intval($p);
	    $n = intval($n);
	    $start = $p*$n;
	    
	    $sql = "select count(1) as n from g_coupon where pid={$pid} {$where} ";
	    $da = $this->query($sql);
	    if (empty($da[0][0]['n'])) {
	        $total = 0;
	        return array();
	    } else {
	       $total = intval($da[0][0]['n']);
	       $sql = "select * from g_coupon where pid={$pid} {$where} order by `{$order}` desc limit {$start},{$n}";
    	   return $this->query($sql);
	    }

	    
	}
	/**
	 * delete
	 *
	 * @param unknown_type $pid
	 * @param unknown_type $cid
	 * @return unknown
	 */
	function deleteCoupon($pid, $cid) {
	    $pid = intval($pid);
	    $cid = intval($cid);
	    $sql = "delete from g_coupon where pid={$pid} and id={$cid}";
	    return $this->query($sql);
	}
	
	/**
	 * 添加coupon
	 *
	 * @param unknown_type $pid
	 * @param unknown_type $arr
	 * @return unknown
	 */
	function addCoupon($pid ,$arr, $time) {
	    $pid = intval($pid);
	    $li = array();
	    foreach ($arr as $ar) {
	        $ar = str_replace(chr(13),'',trim($ar));
	        if (empty($ar)){
	            continue;
	        }
	        $li[] = "($pid,'".mysql_escape_string(trim($ar))."','{$time}')";
	    }
	    if (empty($li)) {
	        return ;
	    }	    
	    $str = join(',',$li);
	    
	    $sql = " INSERT INTO `g_coupon` (`pid`,`code`,`limit_time` ) VALUES $str;";
	    $da = $this->query($sql);
	    return $da;
	}

	function searchDaoguiCaptcha(&$total, $product_kw, $status, $user_name, $code, $time_type, $start_time, $end_time, $page, $per_page, $platform=null){/*{{{*/

		$total = 0;
 
		$database_name = $this->platform_db_map($platform);
		if (empty($database_name)){
			return false;
		}

		$sql = "select SQL_CALC_FOUND_ROWS c.create_time, c.apply_time, c.user_id, c.product_id, c.code, c.status, c.user_name, c.phone, c.birthday, c.address, c.zipcode, c.province, c.city, p.g_name as product_name, u.g_name as ht_user_name from $database_name.g_luckcaptcha as c join $database_name.g_products as p on(c.product_id=p.g_id)
			join $database_name.g_users as u on(c.user_id = u.g_id) where 1=1 ";

		if (!empty($product_kw)){ // 商品名称
			$sql .= sprintf(" and p.g_name like '%%%s%%'", mysql_escape_string($product_kw));
		}
		if (!empty($status)){ // 状态：pre,active,used
			$sql .= sprintf(" and c.status = '%s'", mysql_escape_string($status));
		}
		if (!empty($user_name)){// 领取者姓名
			$sql .= sprintf(" and c.user_name like '%%%s%%'", mysql_escape_string($user_name));
		}
		if (!empty($code)){ // 验证码
			$sql .= sprintf(" and c.code = '%s'", mysql_escape_string($code));
		}
		if (!empty($time_type) && !empty($start_time) && !empty($end_time)){ // 时间
			$time_type = strval($time_type);

			switch($time_type){
				case 'create':
					$sql .= sprintf(" and (c.create_time >= '%s' and c.create_time <= '%s')", mysql_escape_string($start_time), mysql_escape_string($end_time));
					break;
				case 'apply':
					$sql .= sprintf(" and (c.apply_time >= '%s' and c.apply_time <= '%s')", mysql_escape_string($start_time), mysql_escape_string($end_time));
					break;
			}
		}

		$sql .= sprintf(" order by c.id desc limit %d offset %d", intval($per_page), ($page-1)*$per_page);

		$ret = $this->query($sql);
		 
		$sql = 'select FOUND_ROWS() as cnt';
		$total_ret = $this->query($sql);
		$total = (empty($total_ret[0][0]['cnt'])? 0: intval($total_ret[0][0]['cnt']));
		 
		if (empty($ret)){
			return array();
		}

		$info = array();
		foreach($ret as $idx=>$r){
			foreach($r as $d){
				foreach($d as $k=>$v){
					$info[$idx][$k] = $v;
				}
			}
		}

		foreach($info as &$p){
			if ('used' == $p['status']){
				$p['status'] = "已领取({$p['apply_time']})";
			} else if('active' == $p['status']){
				$p['status'] = "未领取";
			}
		}

		return $info;
	}/*}}}*/

	function platform_db_map($platform=null){/*{{{*/
		if (empty($platform)){
			$platform = SystemProperties::$platform;
		}
		$map = array(
			'sina' => 'tryapp_s',
			'renren' => 'tryapp_r',
			'yoka' => 'tryapp_y',
			'myspace' => 'tryapp_m',
		);

		return ((empty($map[$platform]))? null: $map[$platform]);
	}/*}}}*/
}
